<template>
	<view class="page-main">
		<view class="form-box">
			<u--form ref="uForm" :model="taskForm" :rules="rules" labelPosition="left" labelWidth="auto">
				<u-form-item label="任务" prop="taskContent" borderBottom>
					<u--input v-model="taskForm.taskContent" placeholder="请填写" border="none" inputAlign="right" />
				</u-form-item>
				<u-form-item label="亲密值" prop="integral" borderBottom>
					<u--input type="number" v-model="taskForm.integral" placeholder="任务完成可获得" maxlength="9"
						border="none" inputAlign="right" />
				</u-form-item>
				<u-form-item label="重要级别" prop="level" borderBottom>
					<view class="level-button">
						<view v-for="(item,index) in level" :key="index" @click="onLevelButton(index)"
							:class="'level-circle '+(index==currentLevelIndex?'level-select':'')"
							:style="'background-color:'+item.value" />
					</view>
				</u-form-item>
				<u-form-item label="需完成次数" prop="total" borderBottom>
					<view style="display: flex;justify-content: flex-end;">
						<u-number-box v-model="taskForm.total" :min="1" :max="99" integer color="#fff"
							bgColor="#2979ff !important" iconStyle="color: #fff;" />
					</view>
				</u-form-item>
				<u-form-item label="任务需要拍照" borderBottom>
					<view style="display: flex;justify-content: flex-end;">
						<u-switch v-model="taskForm.isUpload" />
					</view>
				</u-form-item>
				<u-form-item label="发布任务图片" labelPosition="top">
					<u-upload ref="uploadFile" accept="media" :fileList="imageValue" multiple :maxCount="3"
						:maxSize="maxFileSzie" @afterRead="onAfterReadFile" @oversize="onOversizeFile"
						@delete="onDeleteFile" />

					<!-- <uni-file-picker ref="file" v-model="imageValue" fileMediatype="image" mode="grid" limit="1"
							:image-styles="imageStyles" :auto-upload="false" @select="select" @success="uploadSuccess"
							@fail="uploadFail" @delete="fileDelete">
							<view class="file-add-background">
								<view class="file-add-icon-background">
									<u--image src="/static/upload-image.png" width="60px" height="60px" />
								</view>
								<text>选择图片</text>
							</view>
						</uni-file-picker> -->
				</u-form-item>
			</u--form>
		</view>
		<view style="margin-top: 80rpx;">
			<u-button type="success" text="立即下发任务" @click="onAdd()" />
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				taskForm: {
					taskContent: null,
					integral: null,
					total: 1,
					level: 0,
					isUpload: false
				},
				currentLevelIndex: 0,
				level: [{
					name: 0,
					value: "#2979ff"
				}, {
					name: 1,
					value: "#19be6b"
				}, {
					name: 2,
					value: "#f5f509"
				}, {
					name: 3,
					value: "#ff9900"
				}, {
					name: 4,
					value: "#fa3534"
				}],
				rules: {
					taskContent: [{
						type: 'string',
						required: true,
						message: '请填写任务内容',
						trigger: ['blur', 'change']
					}],
					integral: [{
						type: 'number',
						required: true,
						message: '请填写任务可获得的亲密值',
						trigger: ['blur', 'change']
					}]
				},
				isEdit: false,
				imageValue: [],
				maxFileSzie: 1024 * 1024 * 10, // 最大文件10M
				imageSelect: false,
				imageStyles: {
					"border": {
						"color": "#eee",
						"width": "2px",
						"style": "solid",
					}
				},
			}
		},
		onLoad(option) {
			if (option.id) {
				this.isEdit = true;
				this.$http.get(`/taskList/get/${option.id}`)
					.then((res) => {
						this.taskForm = res.data
						if (this.taskForm.images) {
							this.imageValue = [{
								url: this.taskForm.images
							}]
						}
					})
			}
		},
		methods: {
			onAdd() {
				if (this.vuex_user.status == 0) {
					uni.$u.toast('请先绑定伴侣');
					return;
				}
				this.$refs.uForm.validate().then(res => {
					uni.showLoading({
						title: '操作中',
						mask: true
					});
					if (this.imageSelect) {
						this.$refs.file.upload();
					} else {
						this.uploadSuccess();
					}

				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			onLevelButton(index) {
				this.currentLevelIndex = index;
				this.taskForm.level = index;
			},
			onAfterReadFile(event) {
				console.log(event);
				let fileList = [].concat(event.file)
				fileList.map(item => {
					this.imageValue.push({
						url: item.thumb,
						fileUrl: item.url,
						status: 'upload'
					})
				})
			},
			onOversizeFile() {
				uni.$u.toast('文件大小不能超过10M');
			},
			uploadSuccess(e) {
				// 1. 获取当前页面栈实例（此时最后一个元素为当前页）
				let pages = getCurrentPages(),
					// 2. 上一页面实例，注意是length长度，所以要想得到上一页面的实例需要 -2
					prevPage = pages[pages.length - 2],
					taskForm = this.taskForm

				taskForm.taskImages = this.imageValue && this.imageValue.length > 0 ? this.imageValue[0].url : null
				taskForm.integral *= 1

				const db = uniCloud.database()
				if (this.isEdit) {
					this.$http.post('/taskList/update', taskForm)
						.then((res) => {
							uni.hideLoading();
							uni.$u.toast('下发成功');

							uni.navigateBack({
								success: () => {
									let list = prevPage.$vm.list
									let index = list.findIndex(item => item._id === taskForm.id)
									list.splice(index, 1, taskForm)
									// if (prevPage.data.curNow == 1) {
									// 	prevPage.onLoad()
									// }
								}
							});
						}).catch((err) => {
							uni.hideLoading();
						})

					return;
				}
				const user = this.vuex_user

				taskForm.userId = user.id
				taskForm.completedById = user.partnerId
				this.$http.post('/taskList/add', taskForm)
					.then((res) => {
						taskForm.id = res.data.id
						uni.hideLoading();
						uni.$u.toast('下发成功');

						uni.navigateBack({
							success: () => {
								prevPage.$vm.list.unshift(taskForm)
							}
						});
					}).catch((err) => {
						uni.hideLoading();
					})
			},
			/**
			 * 文件删除时触发
			 * @param {, index, file, name} event
			 */
			onDeleteFile(event) {
				this.imageValue.splice(event.index, 1)
			},
			//上传失败
			uploadFail(e) {
				uni.hideLoading();
				uni.$u.toast('上传失败')
			},
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		background-color: rgba(255, 255, 255, 0.85);
	}

	.level-button {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.level-circle {
		width: 50rpx;
		height: 50rpx;
		border-radius: 100%;
		margin: 0 10rpx;

		&.level-select {
			border: 5rpx solid #5d5d5d;
			box-sizing: border-box;
		}
	}

	::v-deep .u-upload__button.data-v-69e2a36e {
		margin: 10px 0 0;
	}

	::v-deep .u-upload__wrap__preview.data-v-69e2a36e {
		margin: 10px 8px 0 0;
	}

	::v-deep .u-upload__deletable.data-v-69e2a36e {
		height: 16px;
		width: 16px;
	}

	::v-deep .u-upload__deletable__icon.data-v-69e2a36e {
		transform: scale(0.9);
		-webkit-transform: scale(0.9);
		top: 2px;
		right: 2px;
	}
</style>